package com.woniu.config;

import com.woniu.adapter.MessageRepositoryAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class RabbitMQConfig {

    @Autowired
    private MessageRepositoryAdapter messageRepositoryAdapter;

    @Bean
    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);

        // 设置开启 Mandatory，才能触发回调函数，无论消息推送结果怎么样都强制调用回调函数
        rabbitTemplate.setMandatory(true);

        // RabbitMQ（的Exchange）已收到该消息，我们要更新消息表，将消息状态从【未发送】改为【已发送】。
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            String idString = correlationData.getId();
            if (ack) {
                log.debug("消息[{}]成功发送至 Exchange，将改变其状态至【已发送】", idString);
                messageRepositoryAdapter.changeMessageStatusToSended(Integer.valueOf(idString));
            } else {
                log.debug("消息[{}]未能成功投递至 Exchange。等待定时任务下一轮的发送。", idString);
            }
        });
        return rabbitTemplate;
    }
}
